package com.nulldev.util.security.encryptAPI.impls.des;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.security.encryptAPI.Encryptor;

public class DES extends Encryptor {

	private final static DESCipher des = new DESCipher();

	public DES(final String key) {
		this(DESCipher.passwordToKey(key));
	}

	public DES(final byte[] key) {
		super("encryptapi.legacy.des", new String[]
			{ "DES" }, key);
	}

	@SuppressWarnings("static-access")
	@Override
	public byte[] encryptToBytes(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			if (((byte[]) o).length % 8 != 0) {
				throw new UnsupportedOperationException("encryptToBytes() -> Invalid operation on data. (must be interval of 8!)");
			}
			return des.encrypt((byte[]) o, this.key);
		} else if (o instanceof String) {
			if (((String) o).length() % 8 != 0) {
				throw new UnsupportedOperationException("encryptToBytes() -> Invalid operation on data. (must be interval of 8!)");
			}
			return des.encrypt(((String) o).getBytes(), this.key);
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@SuppressWarnings("static-access")
	@Override
	public String encrypt(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
//			if (((byte[])o).length % 8 != 0) {
//				throw new UnsupportedOperationException("encrypt() -> Invalid operation on data. (must be interval of 8! got: " + ((byte[])o).length + ")");
//			}
			return Base64.encodeBase64String(des.encrypt((byte[]) o, this.key));
		} else if (o instanceof String) {
//			if (((String)o).length() % 8 != 0) {
//				throw new UnsupportedOperationException("encrypt() -> Invalid operation on data. (must be interval of 8! got: " + ((String)o).length() + ")");
//			}
			return Base64.encodeBase64String(des.encrypt(((String) o).getBytes(), this.key));
		} else {
			throw new UnsupportedOperationException("encrypt() -> Unsupported operation on: " + o);
		}
	}

	@SuppressWarnings("static-access")
	@Override
	public String decrypt(String o) {
		Variables.notNullE(o);
		if (o.isEmpty())
			throw new IllegalArgumentException("o is empty!");
		return new String(des.decrypt(Base64.decodeBase64(o), this.key));
	}

	@SuppressWarnings("static-access")
	@Override
	public byte[] decryptToBytes(byte[] o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return des.decrypt(o, this.key);
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public byte[] getKey() {
		return this.key;
	}

	@Override
	public String getKeyAsString() {
		return Base64.encodeBase64String(this.key);
	}

}
